//
// Created by 王筱童 on 2022/5/14.
//

#include "save_maneger.h"
#include "others.h"
#include "redis_server.h"

void save_maneger::save(const std::string &command, const std::vector<std::string> &args, std::size_t db_index) {
    if(!is_reload){
        std::string res=command;
        for(int i=0;i<args.size();i++){
            res+=" ";
            res+=args[i];
        }
        res+='\n';
        out<<"SELECT "<<db_index<<'\n';
        out<<res;
        out.flush();
        if(is_rewirte){

        }
    }
}

asio::awaitable<void> save_maneger::reload() {
    is_reload= true;
    std::string str;
    asio::io_context io;
    asio::ip::tcp::socket socket(server->io_context);
    co_await socket.async_connect(server->acceptor.local_endpoint(),asio::use_awaitable);
    while (std::getline(in,str)){
        str= serialize(str);
        co_await asio::async_write(socket,asio::buffer(str),asio::use_awaitable);
        std::string head(sizeof (std::uint64_t),'\0');
        co_await asio::async_read(socket,asio::buffer(head),asio::use_awaitable);
        auto [len,_]= deserialize_head(head);
        head.resize(len,'\0');
        co_await asio::async_read(socket,asio::buffer(head),asio::use_awaitable);
    }
    is_reload= false;

}

void save_maneger::rewirte() {

}

save_maneger::save_maneger(redis_server *_server):server(_server),out(save_path,std::ios::out|std::ios::app),in(save_path,std::ios::in) {

}
